package com.sso.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sso.entity.Fileparent;
import com.sso.entity.Fileson;
import com.sso.filter.R;
import com.sso.service.impl.FileparentService;
import com.sso.service.impl.FilesonService;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 上传文件控制器
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/19 4:09 下午
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/19 4:09 下午
 * @updateRemark:
 * @version: 1.0
 **/
@CrossOrigin
@RestController
public class UploadController {

    @Value("${file.address}")
    private String address;
    @Autowired
    private FileparentService fileparentService;
    @Autowired
    private FilesonService filesonService;
    @PostMapping("/upload1")
    public R uploadParent(Fileparent fileparent){
        Fileparent byId = fileparentService.getById(fileparent.getMd5());
        if(byId==null){
            fileparent.setAddress(address+fileparent.getMd5()+"//");
            fileparentService.save(fileparent);
            return R.ok();
        }else {
            return R.ok().put("res",1);
        }
    }

    @PostMapping("/uploadTest")
    public R upload(@RequestParam("file")MultipartFile file, Fileson fileson){
        return saveFile(file,fileson);
    }
    private R saveFile(MultipartFile file,Fileson fileson){
        if (file.isEmpty()){
            return R.error();
        }
        //获取上传文件原来的名称
        String filePath =address+fileson.getParentid();
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }
        String h=filePath+"//"+fileson.getChunk();
        File localFile = new File(h);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),localFile);
            fileson.setAddress(h);
            filesonService.save(fileson);
        }catch (IOException e){
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }
    @Transactional
    @SneakyThrows
    @PostMapping("/merge")
    public R merge(String md5){
        Fileparent byId = fileparentService.getById(md5);
        File saveFilePath = new File(address+byId.getName());
        List<Integer> list=new ArrayList<>();
        if(saveFilePath.exists()){
            if(saveFilePath.length()==byId.getSize()){
                return R.ok().put("res",list);
            }
        }
        List<Fileson> list1 = filesonService.list(new QueryWrapper<Fileson>().lambda()
                .eq(Fileson::getParentid, md5).orderByAsc(Fileson::getChunk));
        int x=-1;
        Integer sum = byId.getSum();
        for(int i=1;i<=sum;i++){
            list.add(i);
        }
        for(Fileson fileson:list1){
            if(x!=-1){
                if(x==fileson.getChunk()){
                    filesonService.removeById(fileson.getId());
                    continue;
                }
            }
            x=fileson.getChunk();
            File file=new File(fileson.getAddress());
            if(file.exists()){
                if(file.length()==fileson.getSize()){
                    list.remove(fileson.getChunk());
                }else {
                    filesonService.removeById(fileson.getId());
                    file.delete();
                }
            }
        }
        list1 = filesonService.list(new QueryWrapper<Fileson>().lambda()
                .eq(Fileson::getParentid, md5).orderByAsc(Fileson::getChunk));
        if(!list.isEmpty()){
            return R.ok().put("res",list);
        }
        //生成文件名
        File saveFilePath1 = new File(address+md5);
        //创建文件输出流
        try (FileOutputStream fos = new FileOutputStream(saveFilePath)){
            FileChannel out = fos.getChannel();
            //循环每一个文件块对应的文件
            for(Fileson fileson:list1){
                File file=new File(fileson.getAddress());
                System.out.println(file.getName());
                byte[] bytes = FileUtils.readFileToByteArray(file);
                FileUtils.writeByteArrayToFile(saveFilePath,bytes,true);
            }
            out.close();
        }
        return R.ok().put("res",list);
    }
}
